<?php
/**
 * Created by PhpStorm.
 * Script Name: Media.php
 * Create: 2022/04/15
 * Description: 素材管理
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;

use app\common\model\MediaImage;
use app\common\model\MediaFile;
use app\common\model\MediaText;
use app\common\model\MediaVideo;
use app\common\model\MediaLink;
use app\common\model\Upload;
use app\common\service\MediaGroup as GroupService;
use think\facade\Db;
use think\facade\Log;
use app\constants\Media as MediaConst;
use app\common\model\MediaXml;

class Media extends Bbase
{
    /**
     * @var Upload
     */
    private $uploadM;
    /**
     * @var MediaLink
     */
    private $linkM;
    /**
     * @var MediaImage
     */
    private $imageM;
    /**
     * @var MediaText
     */
    private $textM;
    /**
     * @var MediaFile
     */
    private $fileM;
    /**
     * @var MediaVideo
     */
    private $videoM;

    private $adminId;
    /**
     * @var MediaXml
     */
    private $xmlM;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->uploadM = new Upload();
        $this->imageM = new MediaImage();
        $this->textM = new MediaText();
        $this->fileM = new MediaFile();
        $this->videoM = new MediaVideo();
        $this->linkM = new MediaLink();
        $this->xmlM = new MediaXml();
        $this->adminId = $this->adminInfo['id'];
        $this->assign('config', config('system.upload'));
        set_time_limit(0);
    }

    /**
     * 素材上传
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function uploadPost(){
        if(request()->isPost()) {
            $post_data = input('');
            $res = $this->uploadM->upload($_FILES, Upload::config($post_data['type']), ['uid' => $this->adminInfo['id']]);

            if($res['code']){
                foreach ($res['data'] as $item){
                    $insert_data = [
                        'admin_id' => $item['uid'],
                        'title' => $item['original_name'],
                        'url' => $item['url'],
                        'size' => $item['size'],
                        'ext' => $item['ext'],
                        'location' => $item['location']
                    ];
                    $data = model('media_' . $post_data['type'])->addOne($insert_data);
                }
                $this->success('上传成功');
            }else{
                $this->error($res['msg']);
            }
        }
    }

    /**
     * 删除素材
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function delPost(){
        $post_data = input();
        $ids = $post_data['ids'];
        $model = model('media_'.$post_data['type']);
        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = $model->getOne(['admin_id' => $this->adminInfo['id'], 'id' => $id]);
                if($model->delOne(['admin_id' => $this->adminInfo['id'], 'id' => $id])){
                    !empty($data['location']) && strtolower($data['location']) == 'local' && @unlink($data['path']); //删除本地文件
                }
                //refresh
                $model->getOneByMap(['id' => $data['id'], 'admin_id' => $this->adminId], true, 1);
            }
            $res = true;
            Db::commit();
        }catch (\Exception $e){
            Log::error($e->getMessage());
            Db::rollback();
            $res = false;
        }
        if($res === false){
            $this->error('系统错误，请刷新重试');
        }
        $this->success('删除成功');
    }

    private function getModel($type = 'image'){
        $list = [
            MediaConst::IMAGE => $this->imageM,
            MediaConst::TEXT => $this->textM,
            MediaConst::FILE => $this->fileM,
            MediaConst::VIDEO => $this->videoM,
            MediaConst::LINK => $this->linkM,
            MediaConst::XML => $this->xmlM,
        ];
        return isset($list[$type]) ? $list[$type] : null;
    }

    /**
     * 列表通用action
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function choose(){
        $group_id = input('group_id', -1);
        $type = input('type', MediaConst::TEXT);
        $where = ['admin_id' => $this->adminId];
        $group_id >= 0 && $where['group_id'] = $group_id;
        $search_key = input('search_key', '');
        if($search_key){
            if($type == MediaConst::TEXT){
                $where['title|content'] = ['like', '%'.$search_key.'%'];
            }else{
                $where['title'] = ['like', '%'.$search_key.'%'];
            }
        }

        $data_list = $this->getModel($type)->page(12, $where, ['id' => 'desc'], true, true);
        //dump($data_list);exit;
        $pager = $data_list->appends(['type' => $type, 'search_key' => $search_key])->render();
        $assign = [
            'data_list' => $data_list,
            'type' => $type,
            'pager' => $pager,
            'config' => config('system.upload'),
            'field' => input('field', ''), //目标input框
            'groups' => [0=>'未分组'] + GroupService::getIdToTitle(),
            'group_id' => $group_id
        ];
        return $this->show($assign);
    }

    /**
     * 设置分组
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function setGroupPost(){
        $post_data = input();
        $ids = $post_data['ids'];
        $model = $this->getModel($post_data['type']);
        Db::startTrans();
        try {
            $model->updateByMap(['id' => ['in', $ids], 'admin_id' => $this->adminInfo['id']],
                ['group_id' => $post_data['group_id']]
            );
            $res = true;
            Db::commit();
        }catch (\Exception $e){
            Log::error($e->getMessage());
            Db::rollback();
            $res = false;
        }
        if($res === false){
            $this->error('系统错误，请刷新重试或联系管理员');
        }
        $this->success('操作成功!');
    }
}